// API翻译服务
const express = require('express');
const router = express.Router();
const axios = require('axios');
const { authenticateToken } = require('../middleware/auth');
const Authorization = require('../middleware/authorization');

// 翻译服务提供商配置
const TRANSLATION_PROVIDERS = {
  google: {
    name: 'Google翻译',
    endpoint: 'https://translation.googleapis.com/language/translate/v2',
    method: 'POST',
    authType: 'apiKey'
  },
  baidu: {
    name: '百度翻译',
    endpoint: 'https://fanyi-api.baidu.com/api/trans/vip/translate',
    method: 'GET',
    authType: 'appid'
  },
  deepl: {
    name: 'DeepL翻译',
    endpoint: 'https://api-free.deepl.com/v2/translate',
    method: 'POST',
    authType: 'authKey'
  },
  microsoft: {
    name: '微软翻译',
    endpoint: 'https://api.cognitive.microsofttranslator.com/translate',
    method: 'POST',
    authType: 'subscriptionKey'
  },
  tencent: {
    name: '腾讯翻译',
    endpoint: 'https://tmt.tencentcloudapi.com',
    method: 'POST',
    authType: 'secret'
  }
};

// 语言代码映射
const LANGUAGE_MAPPING = {
  'zh-CN': { google: 'zh-CN', baidu: 'zh', deepl: 'ZH', microsoft: 'zh-Hans', tencent: 'zh' },
  'en-US': { google: 'en', baidu: 'en', deepl: 'EN', microsoft: 'en', tencent: 'en' },
  'ja-JP': { google: 'ja', baidu: 'jp', deepl: 'JA', microsoft: 'ja', tencent: 'ja' },
  'ko-KR': { google: 'ko', baidu: 'kor', deepl: 'KO', microsoft: 'ko', tencent: 'ko' },
  'fr-FR': { google: 'fr', baidu: 'fra', deepl: 'FR', microsoft: 'fr', tencent: 'fr' },
  'de-DE': { google: 'de', baidu: 'de', deepl: 'DE', microsoft: 'de', tencent: 'de' },
  'es-ES': { google: 'es', baidu: 'spa', deepl: 'ES', microsoft: 'es', tencent: 'es' },
  'pt-BR': { google: 'pt', baidu: 'pt', deepl: 'PT', microsoft: 'pt', tencent: 'pt' },
  'ru-RU': { google: 'ru', baidu: 'ru', deepl: 'RU', microsoft: 'ru', tencent: 'ru' },
  'it-IT': { google: 'it', baidu: 'it', deepl: 'IT', microsoft: 'it', tencent: 'it' },
  'nl-NL': { google: 'nl', baidu: 'nl', deepl: 'NL', microsoft: 'nl', tencent: 'nl' },
  'pl-PL': { google: 'pl', baidu: 'pl', deepl: 'PL', microsoft: 'pl', tencent: 'pl' },
  'tr-TR': { google: 'tr', baidu: 'tr', deepl: 'TR', microsoft: 'tr', tencent: 'tr' },
  'vi-VN': { google: 'vi', baidu: 'vie', deepl: 'VI', microsoft: 'vi', tencent: 'vi' },
  'th-TH': { google: 'th', baidu: 'th', deepl: 'TH', microsoft: 'th', tencent: 'th' },
  'ar-SA': { google: 'ar', baidu: 'ara', deepl: 'AR', microsoft: 'ar', tencent: 'ar' },
  'hi-IN': { google: 'hi', baidu: 'hi', deepl: 'HI', microsoft: 'hi', tencent: 'hi' }
};

// 测试API连接
router.post('/translation/test-connection', authenticateToken, Authorization.requireRole(['admin']), async (req, res) => {
  try {
    const { provider, apiKey, apiSecret } = req.body;
    
    if (!provider || !apiKey) {
      return res.status(400).json({
        success: false,
        message: '缺少必要的参数：provider和apiKey'
      });
    }
    
    const providerConfig = TRANSLATION_PROVIDERS[provider];
    if (!providerConfig) {
      return res.status(400).json({
        success: false,
        message: '不支持的翻译服务提供商'
      });
    }
    
    // 测试翻译
    const testText = 'Hello world';
    const sourceLang = 'en';
    const targetLang = 'zh';
    
    const result = await translateText(provider, apiKey, apiSecret, testText, sourceLang, targetLang);
    
    res.json({
      success: true,
      message: 'API连接测试成功',
      data: {
        provider: providerConfig.name,
        testText: testText,
        translatedText: result.translatedText,
        confidence: result.confidence
      }
    });
    
  } catch (error) {
    console.error('API连接测试失败:', error);
    res.status(500).json({
      success: false,
      message: `API连接测试失败: ${error.message}`
    });
  }
});

// 批量翻译文本
router.post('/translation/batch-translate', authenticateToken, Authorization.requireRole(['admin']), async (req, res) => {
  try {
    const { provider, apiKey, apiSecret, texts, sourceLang, targetLang } = req.body;
    
    if (!provider || !apiKey || !texts || !sourceLang || !targetLang) {
      return res.status(400).json({
        success: false,
        message: '缺少必要的参数'
      });
    }
    
    if (!Array.isArray(texts) || texts.length === 0) {
      return res.status(400).json({
        success: false,
        message: 'texts参数必须是非空数组'
      });
    }
    
    const translations = [];
    let successCount = 0;
    let errorCount = 0;
    
    // 分批处理，避免API限制
    const batchSize = 10;
    for (let i = 0; i < texts.length; i += batchSize) {
      const batch = texts.slice(i, i + batchSize);
      
      for (const text of batch) {
        try {
          const result = await translateText(provider, apiKey, apiSecret, text, sourceLang, targetLang);
          translations.push({
            originalText: text,
            translatedText: result.translatedText,
            confidence: result.confidence,
            success: true
          });
          successCount++;
        } catch (error) {
          translations.push({
            originalText: text,
            translatedText: '',
            error: error.message,
            success: false
          });
          errorCount++;
        }
        
        // 添加延迟避免API限制
        await new Promise(resolve => setTimeout(resolve, 100));
      }
    }
    
    res.json({
      success: true,
      message: `批量翻译完成，成功: ${successCount}, 失败: ${errorCount}`,
      data: {
        translations: translations,
        summary: {
          total: texts.length,
          success: successCount,
          error: errorCount
        }
      }
    });
    
  } catch (error) {
    console.error('批量翻译失败:', error);
    res.status(500).json({
      success: false,
      message: `批量翻译失败: ${error.message}`
    });
  }
});

// 获取支持的翻译语言
router.get('/translation/supported-languages', authenticateToken, Authorization.requireRole(['admin']), async (req, res) => {
  try {
    const { provider } = req.query;
    
    if (!provider) {
      return res.status(400).json({
        success: false,
        message: '缺少provider参数'
      });
    }
    
    const supportedLanguages = getSupportedLanguages(provider);
    
    res.json({
      success: true,
      data: {
        provider: TRANSLATION_PROVIDERS[provider]?.name || provider,
        supportedLanguages: supportedLanguages
      }
    });
    
  } catch (error) {
    console.error('获取支持的语言失败:', error);
    res.status(500).json({
      success: false,
      message: `获取支持的语言失败: ${error.message}`
    });
  }
});

// 翻译文本函数
async function translateText(provider, apiKey, apiSecret, text, sourceLang, targetLang) {
  const providerConfig = TRANSLATION_PROVIDERS[provider];
  if (!providerConfig) {
    throw new Error('不支持的翻译服务提供商');
  }
  
  const mappedSourceLang = LANGUAGE_MAPPING[sourceLang]?.[provider] || sourceLang;
  const mappedTargetLang = LANGUAGE_MAPPING[targetLang]?.[provider] || targetLang;
  
  try {
    let response;
    
    switch (provider) {
      case 'google':
        response = await axios.post(providerConfig.endpoint, null, {
          params: {
            q: text,
            source: mappedSourceLang,
            target: mappedTargetLang,
            key: apiKey
          }
        });
        return {
          translatedText: response.data.data.translations[0].translatedText,
          confidence: 0.95
        };
        
      case 'baidu':
        const salt = Date.now();
        const sign = require('crypto').createHash('md5').update(apiKey + text + salt + apiSecret).digest('hex');
        response = await axios.get(providerConfig.endpoint, {
          params: {
            q: text,
            from: mappedSourceLang,
            to: mappedTargetLang,
            appid: apiKey,
            salt: salt,
            sign: sign
          }
        });
        return {
          translatedText: response.data.trans_result[0].dst,
          confidence: 0.90
        };
        
      case 'deepl':
        response = await axios.post(providerConfig.endpoint, null, {
          params: {
            text: text,
            source_lang: mappedSourceLang,
            target_lang: mappedTargetLang
          },
          headers: {
            'Authorization': `DeepL-Auth-Key ${apiKey}`
          }
        });
        return {
          translatedText: response.data.translations[0].text,
          confidence: 0.98
        };
        
      case 'microsoft':
        response = await axios.post(providerConfig.endpoint + `?api-version=3.0&from=${mappedSourceLang}&to=${mappedTargetLang}`, 
          [{ Text: text }],
          {
            headers: {
              'Ocp-Apim-Subscription-Key': apiKey,
              'Content-Type': 'application/json'
            }
          }
        );
        return {
          translatedText: response.data[0].translations[0].text,
          confidence: 0.92
        };
        
      default:
        throw new Error('暂不支持该翻译服务提供商');
    }
    
  } catch (error) {
    console.error(`翻译失败 (${provider}):`, error.response?.data || error.message);
    throw new Error(`翻译服务错误: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 获取支持的语言列表
function getSupportedLanguages(provider) {
  const baseLanguages = ['zh-CN', 'en-US', 'ja-JP', 'ko-KR', 'fr-FR', 'de-DE', 'es-ES', 'pt-BR', 'ru-RU'];
  
  switch (provider) {
    case 'google':
      return [...baseLanguages, 'it-IT', 'nl-NL', 'pl-PL', 'tr-TR', 'vi-VN'];
    case 'baidu':
      return [...baseLanguages, 'th-TH', 'ar-SA', 'hi-IN'];
    case 'deepl':
      return [...baseLanguages, 'it-IT', 'nl-NL', 'pl-PL'];
    case 'microsoft':
      return [...baseLanguages, 'it-IT', 'nl-NL', 'pl-PL', 'tr-TR', 'vi-VN', 'th-TH', 'ar-SA', 'hi-IN'];
    case 'tencent':
      return [...baseLanguages, 'it-IT', 'nl-NL', 'th-TH', 'vi-VN'];
    default:
      return baseLanguages;
  }
}

module.exports = router;